<template>
  <div class="rim-container">
    <div class="rim-header">
      <h1>周边分类管理</h1>
      <el-button type="primary" @click="handleAdd">新增分类</el-button>
    </div>

    <!-- 分类列表 -->
    <el-table
      v-loading="loading"
      :data="categoryList"
      border
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="220" />
      <el-table-column prop="name" label="分类名称" />
      <el-table-column prop="sortOrder" label="排序" width="100" />
      <el-table-column prop="createdTime" label="创建时间" width="180" />
      <el-table-column prop="createdBy" label="创建人" width="120" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button type="danger" size="small" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pageParams.pageNo"
        v-model:page-size="pageParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑分类弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增分类' : '编辑分类'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="formData.sortOrder" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getRimCategory,
  addPeripheralProductsClassify,
  deletePeripheralProductsClassify,
  updatePeripheralProductsClassify
} from "@/api/rim";

// 列表数据和加载状态
const categoryList = ref([]);
const loading = ref(false);
const total = ref(0);

// 分页参数
const pageParams = reactive({
  pageNo: 1,
  pageSize: 10
});

// 表单相关
const dialogVisible = ref(false);
const dialogType = ref("add"); // 'add' 或 'edit'
const formRef = ref(null);
const formData = reactive({
  id: "",
  name: "",
  sortOrder: 1
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
  ],
  sortOrder: [{ required: true, message: "请输入排序值", trigger: "change" }]
};

// 获取分类列表
const fetchCategoryList = async () => {
  loading.value = true;
  try {
    const res = await getRimCategory(pageParams);
    categoryList.value = res.data.result || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error("获取分类列表失败:", error);
    ElMessage.error("获取分类列表失败");
  } finally {
    loading.value = false;
  }
};

// 分页变化
const handleSizeChange = size => {
  pageParams.pageSize = size;
  fetchCategoryList();
};

const handleCurrentChange = current => {
  pageParams.pageNo = current;
  fetchCategoryList();
};

// 新增分类
const handleAdd = () => {
  dialogType.value = "add";
  resetForm();
  dialogVisible.value = true;
};

// 编辑分类
const handleEdit = row => {
  dialogType.value = "edit";
  resetForm();
  Object.assign(formData, {
    id: row.id,
    name: row.name,
    sortOrder: row.sortOrder
  });
  dialogVisible.value = true;
};

// 删除分类
const handleDelete = row => {
  ElMessageBox.confirm(`确认要删除分类"${row.name}"吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        await deletePeripheralProductsClassify(row.id);
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        fetchCategoryList();
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  formData.id = "";
  formData.name = "";
  formData.sortOrder = 1;
};

// 提交表单
const submitForm = async () => {
  formRef.value.validate(async valid => {
    if (valid) {
      try {
        if (dialogType.value === "add") {
          // 调用新增分类接口
          await addPeripheralProductsClassify({ name: formData.name });
          ElMessage.success("新增成功");
        } else {
          // 调用修改分类接口
          await updatePeripheralProductsClassify({
            id: formData.id,
            name: formData.name,
            sortOrder: formData.sortOrder
          });
          ElMessage.success("编辑成功");
        }
        dialogVisible.value = false;
        fetchCategoryList();
      } catch (error) {
        console.error(
          dialogType.value === "add" ? "新增失败:" : "编辑失败:",
          error
        );
        ElMessage.error(dialogType.value === "add" ? "新增失败" : "编辑失败");
      }
    }
  });
};

// 页面加载时获取数据
onMounted(() => {
  fetchCategoryList();
});
</script>

<style scoped>
.rim-container {
  padding: 20px;
}

.rim-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
